package point

import (
	"os/exec"
	"regexp"
	"strings"
)

type WanXDnsPoint struct {
	index int
}

var wanxDns string

func NewWanXDnsPoint() *WanXDnsPoint { return &WanXDnsPoint{} }

func (s *WanXDnsPoint) Get() any {

	var interfaceName string

	if s.index == 0 {
		interfaceName = "eth1"
	} else if s.index == 1 {
		interfaceName = "eth2"
	} else {
		return ""
	}

	getConnectionUuid := func(iface string) string {
		cmd := exec.Command("nmcli", "connection")
		output, err := cmd.Output()
		if err != nil {
			return ""
		}

		lines := strings.Split(string(output), "\n")

		pattern := `\s*(.*?)\s+\s+(.*?)\s+\s+(.*?)\s+\s+(.*?)\s*$`
		re := regexp.MustCompile(pattern)

		for _, line := range lines {
			if line == "" {
				continue
			}
			parts := re.FindStringSubmatch(line)
			if len(parts) != 5 {
				continue
			}
			// name, uuid, typ, device := parts[1], parts[2], parts[3], parts[4]
			// fmt.Printf("NAME: %s, UUID: %s, TYPE: %s, DEVICE: %s\n", name, uuid, typ, device)

			if parts[4] == iface {
				return parts[2]
			}
		}

		return ""
	}

	getDnsByInterface := func(uuid string, key string) string {
		if uuid == "" {
			return uuid
		}

		cmd := exec.Command("nmcli", "connection", "show", uuid)
		output, err := cmd.Output()
		if err != nil {
			return ""
		}

		lines := strings.Split(string(output), "\n")

		pattern := `\s*(.*?)\s+\s+(.*?)\s*$`
		re := regexp.MustCompile(pattern)

		for _, line := range lines {
			if line == "" {
				continue
			}
			parts := re.FindStringSubmatch(line)
			if len(parts) != 3 {
				continue
			}
			// fmt.Println("key -->", parts[1])
			// fmt.Println("val -->", parts[2])
			if parts[1] == key {
				return parts[2]
			}
		}

		return ""
	}

	return getDnsByInterface(getConnectionUuid(interfaceName), "IP4.GATEWAY:")
}

func (s *WanXDnsPoint) Set(val ...any) bool {
	if len(val) < 1 {
		return false
	}

	if dns, ok := val[0].(string); ok {
		wanxDns = dns
	}

	return true
}

func (s *WanXDnsPoint) SetRoute(str string) PointInterface {
	s.index = int(str[len("wan")]) - '0'
	return s
}
